class Solution {
    public static class ListNode {
        int val;
        ListNode next;
        ListNode() {}
        ListNode(int val) { this.val = val; }
        ListNode(int val, ListNode next) { this.val = val; this.next = next; }
    }
    
    public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
        ListNode dummy = new ListNode(0);
        ListNode p1 = list1;
        ListNode p2 = list2;
        ListNode p = dummy;
        while(p1 != null && p2 != null) {
            if (p1.val > p2.val){
                p.next = p2;
                p2 = p2.next;
            }else{
                p.next = p1;
                p1 = p1.next;
            }
            p = p.next;
        }
        if (p1 != null){
            p.next = p1;
        }
        if (p2 != null){
            p.next = p2;
        }
        return dummy.next;
    }
    
    // 辅助方法：打印链表
    public static void printList(ListNode head) {
        ListNode current = head;
        while (current != null) {
            System.out.print(current.val);
            if (current.next != null) {
                System.out.print(" -> ");
            }
            current = current.next;
        }
        System.out.println();
    }
    
    // 测试方法
    public static void main(String[] args) {
        // 创建第一个链表: 1 -> 3 -> 5
        ListNode l1 = new ListNode(1, new ListNode(3, new ListNode(5)));
        // 创建第二个链表: 2 -> 4 -> 6
        ListNode l2 = new ListNode(2, new ListNode(4, new ListNode(6)));
        
        Solution solution = new Solution();
        // 合并链表
        ListNode mergedList = solution.mergeTwoLists(l1, l2);
        // 打印合并后的链表
        printList(mergedList);
    }
}